package com.siyoumi.app.sys.service.wx_center;

import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * 公众号授权模式回复处理
 */
@Slf4j
public class CenterHandlerClient
        extends CenterHandlerCorp {
    /**
     * 对密文进行解密
     *
     * @param encTxt
     */
    @Override
    @SneakyThrows
    public String decryptTxt(String encTxt) {
        SysAccsuperConfig entityConfigParent = SysAccsuperConfigService.getBean().getXConfigWxOpenParent(getEntityConfig().getX());
        String key = entityConfigParent.getAconfig_key();

        String txt = "";
        byte[] original;
        try {
            byte[] aesKey = Base64.decodeBase64(key + "=");

            // 设置解密模式为AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
            cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);

            // 使用BASE64对密文进行解码
            byte[] encrypted = Base64.decodeBase64(encTxt);

            // 解密
            original = cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        String fromAppId;
        try {
            // 去除补位字符
            byte[] bytes = PKCS7Encoder.decode(original);

            //获取内容长度
            byte[] xmlLenByte = Arrays.copyOfRange(bytes, 16, 20);
            int xmlLength = corpByteToInt(xmlLenByte);

            txt = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), StandardCharsets.UTF_8);
            fromAppId = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        // receiveid不相同的情况
        if (!fromAppId.equals(entityConfigParent.getAconfig_app_id())) {
            XValidator.err(50302, XStr.format("aes解密失败, {0}, {1}", fromAppId, entityConfigParent.getAconfig_app_id()));
        }

        return txt;
    }
}
